package me.lx.tools

import android.util.Log
import me.lx.http.HttpLoggingInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 *  author: luoXiong
 *  e-mail: 382060748@qq.com
 *  date: 2021/7/19 17:25
 *  version: 1.0
 *  desc:
 */
object RetrofitClient {
    private lateinit var okHttpClient: OkHttpClient
    private lateinit var mRetrofit: Retrofit

    fun init() {
        createAppRequestOkHttpClient()
        createRetrofit()
    }

    private fun createRetrofit() {
        val builder = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("http://daily.webuy.ai")
            //  .addConverterFactory()//不同的域名，需要添加不同的转换器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//不同的域名，需要添加不同的转换器
        //   .addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(Schedulers.io())) // 子线程请求接口
        val retrofit = builder.build()
        mRetrofit = retrofit
    }

    fun getRetrofit(): Retrofit {
        return mRetrofit
    }

    fun getOkHttpClient(): OkHttpClient {
        return okHttpClient
    }

    private fun createAppRequestOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()
        //设置超时
        var time = 35L
        builder.connectTimeout(time, TimeUnit.SECONDS)
            .readTimeout(time, TimeUnit.SECONDS)
            .writeTimeout(time, TimeUnit.SECONDS)
            //错误重连
            .retryOnConnectionFailure(true) // 改成true就会没错误
        //Log拦截器
        // BuildConfig.DEBUG
        //stetho调试器
        val logging =
            HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
                override fun log(message: String?) {
                    Log.w("luoxiong OkHttp -> ", "$message")
                }
            })
        logging.setLevel(HttpLoggingInterceptor.Level.BASIC)   //BASIC : url成功返回
        builder.addInterceptor(logging)
//            .addNetworkInterceptor(JlH5Container.getOkHttpCacheInterceptor())
//            .cache(JlH5Container.getOkhttpCache())

        //初始化ssl ,@GlideModule 必须要使用
        //registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));

        initSslSecure(builder) // 才能加载https的图片

        //3、添加Post请求参数拦截器
        okHttpClient = builder.build()

        return okHttpClient
    }

    fun initSslSecure(builder: OkHttpClient.Builder) {
        try {
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                @Throws(CertificateException::class)
                override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
                }

                @Throws(CertificateException::class)
                override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
                }

                override fun getAcceptedIssuers(): Array<X509Certificate> {
                    return arrayOf()
                }
            })
            // val sslContext = SSLContext.getInstance("SSL") // 如果是SSL,在素材页面保存视频会报错:
            // javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, trustAllCerts, java.security.SecureRandom())
            val sslSocketFactory = sslContext.socketFactory
            builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
            builder.hostnameVerifier(HostnameVerifier { hostname, session -> true })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}